package logic

import (
	"context"
	"errors"
	"video-guard/models/cache"
	"video-guard/models/mysql"

	"video-guard/videorpc/internal/svc"
	"video-guard/videorpc/videorpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *videorpc.LoginRequest) (*videorpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	var login mysql.UserInfo
	err := login.LoginUser(mysql.DB, in.PhoneNum)
	if err != nil {
		return nil, errors.New("账号不存在")
	}
	if in.LoginType == 1 {
		if in.Password != login.Password {
			return nil, errors.New("密码错误")
		}
	} else if in.LoginType == 2 {
		result, _ := cache.Rdb.Get(cache.Ctx, "sendSms"+in.PhoneNum).Result()
		if result == "" {
			return nil, errors.New("未发送短信")
		}

		if in.SendSms != result {
			return nil, errors.New("短信错误")
		}
	}
	return &videorpc.LoginResponse{
		UserId: int64(login.ID),
	}, nil
}
